/*
* websocket 封装，处理股票实时数据
* */
var wsclient;
var WS = {};
WS.init = function (wsurl) {
    if(wsclient){wsclient.close();}
    wsclient = new WebSocket(wsurl);
    //onopen监听连接打开
    wsclient.onopen = function (evt) {
        console.log('ws connected');
        console.log(evt);
    };
    //onmessage 监听服务器数据推送
    wsclient.onmessage = function (evt) {
        var dataJson = JSON.parse(evt.data);
        if(dataJson.msgtype == 'fiveTradeData-'+currentSid){
            dealFiveTradeData(dataJson);
        }else if(dataJson.msgtype == 'tradeLine-'+currentSid){
            dealTradeLineData(dataJson);
        }
    };
    //监听连接关闭
    wsclient.onclose = function (evt) {
        console.log("Disconnected");
    };
    //监听连接错误信息
    wsclient.onerror = function (evt, e) {
        console.log('Error occured: ' + evt.data);
    };
};

//处理五档数据
function dealFiveTradeData(data){
    //买入数据
    var buyHtmlStr = '';
    for(var i=0;i<data.buy.length;i++){
        buyHtmlStr += '<tr onclick="changePrice(this)" class="color-gray9"><td>'+data.buy[i].name+'</td><td>'+data.buy[i].price+'</td><td>'+data.buy[i].num+'</td></tr>';
    }
    $('#buyfList').html(buyHtmlStr);

    var saleHtmlStr = '';
    for(var i=0;i<data.sale.length;i++){
        saleHtmlStr += '<tr  onclick="changePrice(this)" class="color-gray9"><td>'+data.sale[i].name+'</td><td>'+data.sale[i].price+'</td><td>'+data.sale[i].num+'</td></tr>';
    }
    $('#salefList').html(saleHtmlStr);
}
//处理分时图数据
function dealTradeLineData(data){
    var len = fsLineTimes.length-1;
    if(fsLineTimes[len] == data.time){
        fsLinePrice[len] = data.price;
    }else{
        fsLineTimes.push(data.time);
        fsLinePrice.push(data.price);
    }

    createLine(fsLineTimes,fsLinePrice);
}


